//
//  User.m
//  NewsReader
//
//  Created by blacksun on 10-10-18.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "User.h"
#import "URLAddress.h"
#import "ModelParseUtil.h"
NSString * NSCustomError = @"com.ipoint.CustomError";


@implementation User

@synthesize userId;
@synthesize deviceId;
@synthesize email;
@synthesize nickName;
@synthesize passwd;  
@synthesize area;
@synthesize sectionIds;
@synthesize lastLoginDate;
@synthesize mySections;
@synthesize feedSizePerRequest;
@synthesize saveFeedDays;
@synthesize requestImage;
@synthesize needUpdateSections;
@synthesize optimizeContent;
@synthesize httpUtils;

- (id)init{
	if (self = [super init]) {
		self.requestImage = YES;
		self.feedSizePerRequest = 20;
		self.saveFeedDays = 3;
		self.optimizeContent = YES;
		self.userId = kUser_defaultUserId;
		self.deviceId = [[UIDevice currentDevice] uniqueIdentifier];
		self.httpUtils = [NSMutableArray array];
		self.needUpdateSections = YES;
		return self;
	}
	return nil;
}

- (BOOL)anonymousRegister{
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	NSURL *url = [[NSURL alloc] initWithString:[URLAddress anonymousRegister:self.deviceId]];
	NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
	[request setTimeoutInterval:kRequestTimeOutOnLoading];
	NSError *error = [NSError errorWithDomain:NSCustomError code:0 userInfo:nil];
	NSData * responseData= [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
	[url release];
	[request release];
	if (![[error domain] isEqualToString:NSCustomError]) {
		NSLog(@"error:%@,%d",[error domain],[error code]);
		delegate.isGFW = YES;
		return NO;
	}
	
	NSString *responseStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	//NSLog(@"response = %@",responseStr);
	NSDictionary * responseDict = [responseStr JSONValue];
	NSArray *sectionsArray = [responseDict objectForKey:kDefaultSections];
	self.mySections = [ModelParseUtil parseSectionsFromJsonArray:sectionsArray];
	self.userId = [NSString  stringWithFormat:@"%@",[responseDict objectForKey:kUserId]];
	[responseStr release];
	return YES;
}



- (BOOL )updateMySections{
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	NSMutableArray *ids = [[NSMutableArray alloc] init];
	for (Section *selected in mySections) {
		[ids addObject:[NSString stringWithFormat:@"%@", selected.sectionId]];
	}
	NSString *idStrs = [[NSString alloc] initWithFormat:@"%@",[ids componentsJoinedByString:@","]];
	NSString *urlStr = [URLAddress getMySections:idStrs forMe:self.userId];
	
	[idStrs release];
	[ids release];
	
	NSURL *url = [[NSURL alloc] initWithString:urlStr];
	
	NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
	[request setTimeoutInterval:kRequestTimeOutOnLoading];
	NSError *error = [NSError errorWithDomain:NSCustomError code:0 userInfo:nil];
	NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
	[request release];
	[url release];
	if (![[error domain] isEqualToString:NSCustomError]) {
		NSLog(@"error:%@,%d",[error domain],[error code]);
		delegate.isGFW = YES;
		return NO;
	}
	NSString *responseStr = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
	//NSLog(@"response=%@",responseStr);
	NSDictionary * responseDict = [responseStr JSONValue];
	NSArray *sectionsArray = [responseDict objectForKey:@"sections"];
	NSMutableArray *newSections = [ModelParseUtil parseSectionsFromJsonArray:sectionsArray];
	for (int i=0; i<[mySections count]; i++) {
		Section *old = [mySections objectAtIndex:i];
		for (int j=0; j<[newSections count]; j++) {
			Section *temp = [newSections objectAtIndex:j];
			if ([temp.sectionId isEqualToString:old.sectionId]) {
				old.oldImageUrl = old.lastFeedImageUrl;
				old.lastFeedTitle = temp.lastFeedTitle;
				old.lastFeedImageUrl = temp.lastFeedImageUrl;
				old.currentMaxId = temp.currentMaxId;
				break;
			}
		}
	}
	[responseStr release];
	
	return YES;
}



- (void)encodeWithCoder:(NSCoder *)encoder{
	//NSLog(@"encoder size=%d",[self.mySections count]);
	[encoder encodeObject:self.userId forKey:kUser_UserId];
	[encoder encodeObject:self.deviceId forKey:kUser_DevicdeId];
	[encoder encodeObject:self.email forKey:kUser_Email];
	[encoder encodeObject:self.nickName forKey:kUser_NikeName];
	[encoder encodeObject:self.passwd forKey:kUser_Passwd];
	[encoder encodeObject:self.area forKey:kUser_Area];
	[encoder encodeObject:self.mySections forKey:kUser_Sections];
	[encoder encodeObject:self.lastLoginDate forKey:kUser_LastLoginDate];
	[encoder encodeInteger:self.feedSizePerRequest forKey:kUser_feedSize];
	[encoder encodeInteger:self.saveFeedDays forKey:kUser_feedDays];
	[encoder encodeBool:self.requestImage forKey:kUser_requestImage];
	[encoder encodeBool:self.needUpdateSections forKey:kUser_needUpdateSections];
	[encoder encodeBool:self.optimizeContent forKey:kUser_optimizeContent];
	
}
- (id)initWithCoder:(NSCoder *)decoder{
	if (self = [super init]) {
		self.userId = [decoder decodeObjectForKey:kUser_UserId];
		self.deviceId = [decoder decodeObjectForKey:kUser_DevicdeId];
		self.email = [decoder decodeObjectForKey:kUser_Email];
		self.nickName = [decoder decodeObjectForKey:kUser_NikeName];
		self.passwd = [decoder decodeObjectForKey:kUser_Passwd];
		self.area = [decoder decodeObjectForKey:kUser_Area];
		self.mySections = [decoder decodeObjectForKey:kUser_Sections];
		self.lastLoginDate = [decoder decodeObjectForKey:kUser_LastLoginDate];
		self.feedSizePerRequest = [decoder decodeIntegerForKey:kUser_feedSize];
		self.saveFeedDays = [decoder decodeIntegerForKey:kUser_feedDays];
		self.requestImage = [decoder decodeBoolForKey:kUser_requestImage];
		self.needUpdateSections = [decoder decodeBoolForKey:kUser_needUpdateSections];
		self.optimizeContent = [decoder decodeBoolForKey:kUser_optimizeContent];
		//NSLog(@"decoder size=%d",[self.mySections count]);
	}
	return self;
}


-(void) dealloc{
	[self.userId release];
	[self.deviceId release];
	[self.email release];
	[self.nickName release];
	[self.passwd release];
	[self.area release];
	[self.sectionIds release];
	[self.lastLoginDate release];
	[self.mySections release];
	[self.httpUtils makeObjectsPerformSelector:@selector(stopHttpConnection)];
	[self.httpUtils release];
	[super dealloc];
}

@end
